﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using System.Web;
using System.Web.Configuration;
using DoeObjects;

namespace DoeLibsMVC
{
	public class DailyChecks
	{
		private Timer _dailyCheck = new Timer();

		private TimeSpan _granularity;// = new TimeSpan(0, 30, 0);
		private TimeSpan _checkNight;// = new TimeSpan(2, 0, 0);
		private TimeSpan _checkNightTo;
		private TimeSpan _checkMorning;// = new TimeSpan(7, 0, 0);
		private TimeSpan _checkMorningTo;

		public DailyChecks()
		{
			_granularity = TimeSpan.Parse(WebConfigurationManager.AppSettings["Granularity"]);

			_checkNight = TimeSpan.Parse(WebConfigurationManager.AppSettings["NightCheckTime"]);
			TimeSpan temp = _checkNight.Add(_granularity);
			_checkNightTo = new TimeSpan(temp.Hours, temp.Minutes, temp.Seconds);

			_checkMorning = TimeSpan.Parse(WebConfigurationManager.AppSettings["MorningCheckTime"]);
			temp = _checkMorning.Add(_granularity);
			_checkMorningTo = new TimeSpan(temp.Hours, temp.Minutes, temp.Seconds);

			_dailyCheck = new Timer { Enabled = false, AutoReset = true, Interval = _granularity.TotalMilliseconds };
			_dailyCheck.Elapsed += dailyCheck_Elapsed;
		}

		public void Start()
		{
			_dailyCheck.Start();
		}

		public void Stop()
		{
			_dailyCheck.Stop();
		}

		private void dailyCheck_Elapsed(object sender, ElapsedEventArgs e)
		{
			TimeSpan now = DateTime.Now.TimeOfDay;
			// Night
			if (checkIfInTimeSpan(now, _checkNight, _checkNightTo))
			{
				Loan.handleExpiredLoans();
                Reservation.cancelReservationsAtEndOfSemester();
                Reservation.handleExpiredReservations();
				User.handleExpiredUsers();
			}
			// Morning
			else if (checkIfInTimeSpan(now, _checkMorning, _checkMorningTo))
			{
				MailManager.sendQueuedMails();
			}
		}

		private static bool checkIfInTimeSpan(TimeSpan timeToCheck, TimeSpan from, TimeSpan to)
		{
			if (TimeSpan.Compare(from, to) == 0)
				if (timeToCheck == from) return true;
				else return false;
			else if (TimeSpan.Compare(from, to) == 1)
				if ((timeToCheck >= from) || (timeToCheck < to)) return true;
				else return false;
			else
				if ((timeToCheck >= from) && (timeToCheck < to)) return true;
				else return false;
		}
	}
}